/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers.Beans;

import Controllers.AbstractController;
import Entities.Message;
import Entities.Student;
import Entities.User;
import Entities.UserMessages;
import Entities.UserMessagesPK;
import Facades.MessageFacade;
import Facades.StudentFacade;
import Facades.UserFacade;
import Facades.UserMessagesFacade;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Named;

/**
 * Bean de Mensajeria
 *
 * @author royCalderon
 */
@Named(value = "messagesBean")
@SessionScoped
public class MessagesBean extends AbstractController<Message> implements Serializable {

    //OJOOOO con el extends abstract facade
    @EJB
    private MessageFacade ejbFacade_Message;
    @EJB
    private UserFacade ejbFacade_User;
    @EJB
    private UserMessagesFacade ejbFacade_UserMessages;
    @EJB
    private StudentFacade ejbFacade_Student;
    private User userSelected;
    private List<User> usersAutoComplete;
    private List<UserMessages> usersNewMessages;
    private UserMessages userMessages;
    private FacesContext context;
    //For Message Mode
    private boolean multiMessageMode;
    private boolean singleMessageMode;

    public MessagesBean() {
        super(Message.class);
        if (getSelected() == null) {
            prepareCreate(null);
        }
        userMessages = new UserMessages();
        context = FacesContext.getCurrentInstance();
        multiMessageMode = false;
        singleMessageMode = true;
    }

    public boolean isMultiMessageMode() {
        return multiMessageMode;
    }

    public void setMultiMessageMode(boolean multiMessageMode) {
        this.multiMessageMode = multiMessageMode;
    }

    public boolean isSingleMessageMode() {
        return singleMessageMode;
    }

    public void setSingleMessageMode(boolean singleMessageMode) {
        this.singleMessageMode = singleMessageMode;
    }

    public User getUserSelected() {
        return userSelected;
    }

    public void setUserSelected(User userSelected) {
        if (userSelected != null) {
            this.userSelected = userSelected;
        }
    }

    public MessageFacade getEjbFacade_Message() {
        return ejbFacade_Message;
    }

    public void setEjbFacade_Message(MessageFacade ejbFacade_Message) {
        this.ejbFacade_Message = ejbFacade_Message;
    }

    public UserFacade getEjbFacade_User() {
        return ejbFacade_User;
    }

    public void setEjbFacade_User(UserFacade ejbFacade_User) {
        this.ejbFacade_User = ejbFacade_User;
    }

    public UserMessagesFacade getEjbFacade_UserMessages() {
        return ejbFacade_UserMessages;
    }

    public void setEjbFacade_UserMessages(UserMessagesFacade ejbFacade_UserMessages) {
        this.ejbFacade_UserMessages = ejbFacade_UserMessages;
    }

    public StudentFacade getEjbFacade_Student() {
        return ejbFacade_Student;
    }

    public void setEjbFacade_Student(StudentFacade ejbFacade_Student) {
        this.ejbFacade_Student = ejbFacade_Student;
    }

    public List<User> getUsersAutoComplete() {
        return usersAutoComplete;
    }

    public void setUsersAutoComplete(List<User> usersAutoComplete) {
        this.usersAutoComplete = usersAutoComplete;
    }

    public FacesContext getContext() {
        return context;
    }

    public void setContext(FacesContext context) {
        this.context = context;
    }

    public UserMessages getUserMessages() {
        return userMessages;
    }

    public void setUserMessages(UserMessages userMessages) {
        this.userMessages = userMessages;
    }

    public List<UserMessages> getUsersNewMessages() {
        return usersNewMessages;
    }

    public void setUsersNewMessages(List<UserMessages> usersNewMessages) {
        this.usersNewMessages = usersNewMessages;
    }

    /**
     * Get all Messages
     *
     * @author royCalderon
     */
    public List<Message> getAllMessageUSer() {
        if (userSelected != null) {
            return ejbFacade_Message.getMessageUser(ejbFacade_Message.getIdCurrentUser(), userSelected.getId());
        } else {
            return null;
        }
    }

    /**
     * Validate User
     *
     * @author royCalderon
     */
    public boolean validateMessage(int userId) {
        if (userId == ejbFacade_Message.getIdCurrentUser()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * autoComplete userName
     *
     * @author royCalderon
     */
    public List<User> completeUser(String query) {
        usersAutoComplete = new ArrayList<User>();
        for (Student s : ejbFacade_Student.findAll()) {
            if (s.getFullName().toLowerCase().contains(query.toLowerCase())) {
                //Agregar el usuario
                User userSelectedAux = ejbFacade_User.FindbyId(s.getUserid().getId());
                usersAutoComplete.add(userSelectedAux);
            }
        }
        return usersAutoComplete;
    }

    /**
     * get Users that wrote new Messages...
     *
     * @author royCalderon
     */
    public List<User> getNewUsersMessages() {
        //usersMessages List
        usersAutoComplete = new ArrayList<User>();
        usersNewMessages = ejbFacade_UserMessages.getUnreadUserMessages(ejbFacade_User.getIdCurrentUser());
        for (UserMessages usersMessagesAux : usersNewMessages) {
            usersAutoComplete.add(ejbFacade_User.FindbyId(usersMessagesAux.getMessage().getUserid().getId()));
        }
        return usersAutoComplete;
    }

    /**
     * Edit UsersMessage From (U)nread 2 (R)ead
     *
     * @author royCalderon
     */
    void updateMessageRead() {
        
        
    }

    /**
     * Sends The Message from one user to another...
     *
     * @author royCalderon
     */
    public void send(ActionEvent event) {
        if (userSelected != null) {
            if (!getSelected().getBody().isEmpty()) {
                getSelected().setDate(new Date());
                getSelected().setTittle("Directo");
                getSelected().setUserid(ejbFacade_User.find(ejbFacade_User.getIdCurrentUser()));
                ejbFacade_Message.create(super.getSelected());
                userMessages.setUserMessagesPK(new UserMessagesPK(userSelected.getId(), ejbFacade_Message.getIdLastMessage()));
                userMessages.setStatus("U");
                ejbFacade_UserMessages.create(userMessages);
                prepareCreate(null);
                userMessages = new UserMessages();

                //context.addMessage(ejbFacade.getIdCurrentUser().toString(), new FacesMessage(FacesMessage.SEVERITY_INFO, "Mensaje Enviado", "Tu mensaje a sido enviado correctamente"));

            } else {
                //context.addMessage(ejbFacade.getIdCurrentUser().toString(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "Mensaje Fallido", "El mensaje no pudo ser enviado, vuelva a intentarlo"));
            }
        } else {
            //context.addMessage(ejbFacade.getIdCurrentUser().toString(), new FacesMessage(FacesMessage.SEVERITY_WARN, "Selecciona un Usuario", "Es necesario seleccionar un usuario para poder enviar un mensaje"));
        }
    }

    /**
     * Sends The Message to everyone
     *
     * @author royCalderon
     */
    public void send2multi(ActionEvent event) {
        if (!getSelected().getBody().isEmpty()) {
            getSelected().setDate(new Date());
            getSelected().setTittle("Difusion");
            getSelected().setUserid(ejbFacade_User.find(ejbFacade_User.getIdCurrentUser()));
            ejbFacade_Message.create(super.getSelected());

            for (Student studentIterator : ejbFacade_Student.findAll()) {
                if (studentIterator.getUserid().getId() == ejbFacade_User.getIdCurrentUser()) {
                    break;
                }
                userMessages.setUserMessagesPK(new UserMessagesPK(studentIterator.getUserid().getId(), ejbFacade_Message.getIdLastMessage()));
                userMessages.setStatus("U");
                ejbFacade_UserMessages.create(userMessages);
                prepareCreate(null);
                userMessages = new UserMessages();
            }
        }
    }

    /**
     * Change message mode (NOT NEEDED)
     *
     * @author royCalderon
     */
    public void changeModal2multi() {
        multiMessageMode = true;
        singleMessageMode = false;
    }

    public void changeModal2single() {
        multiMessageMode = false;
        singleMessageMode = true;
    }
}
